package im.starchat.chat.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import com.umeng.analytics.MobclickAgent;
import im.starchat.chat.R;
import im.starchat.chat.impl.IActivityBase;
import im.starchat.chat.utils.ActivityHelper;
import im.starchat.chat.utils.ActivityManager;

public class BaseActivity extends ActionBarActivity implements IActivityBase {
    // 手势返回
    private static final int FLING_MIN_DISTANCE = 100;// 移动最小距离(dp)
    private static final int FLING_MIN_VELOCITY = 700;// 移动最小速度

    private Toolbar mActionBarToolbar;
    private VelocityTracker mVelocityTracker;
    private MotionEvent mCurrentDownEvent;
    private int mMaximumVelocity;
    private int mTouchSlop;
    boolean isDrag = false;
    private ActivityHelper mActivityHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTouchSlop = getResources().getDimensionPixelSize(R.dimen.touch_slop);
        final ViewConfiguration configuration = ViewConfiguration.get(getApplicationContext());
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
        mActivityHelper = new ActivityHelper(this);
        ActivityManager.getInstance().addActivity(this);
        hideSoftInputFromWindow();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
//        getActionBarToolbar();
    }

    private void hideSoftInputFromWindow(){
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);
    }


//    public Toolbar getActionBarToolbar() {
//        if (mActionBarToolbar == null) {
//            mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
//            if (mActionBarToolbar != null) {
//                setSupportActionBar(mActionBarToolbar);
//            }
//        }
//        return mActionBarToolbar;
//    }

    protected int getScreenHeight() {
        return findViewById(android.R.id.content).getHeight();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //Log.d("ges", "dispatchTouchEvent x=" + event.getX() + " y=" + event.getY());
        if (isOnGestureBack(event)) {
            final int action = event.getAction() & MotionEventCompat.ACTION_MASK;

            if (mVelocityTracker == null) {
                mVelocityTracker = VelocityTracker.obtain();
            }
            mVelocityTracker.addMovement(event);

            switch (action) {
                case MotionEvent.ACTION_DOWN: {
                    // Log.d("ges", "dispatchTouchEvent ACTION_DOWN");

                    if (mCurrentDownEvent != null) {
                        mCurrentDownEvent.recycle();
                    }
                    mCurrentDownEvent = MotionEvent.obtain(event);

                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    if (mCurrentDownEvent == null) {
                        mCurrentDownEvent = MotionEvent.obtain(event);
                    }

                    final float x = MotionEventCompat.getX(event, 0);
                    final float xDiff = x - mCurrentDownEvent.getX();
                    final float y = MotionEventCompat.getY(event, 0);
                    final float yDiff = Math.abs(y - mCurrentDownEvent.getY()/*mLastMotionY*/) * 2;
                    if ((xDiff > (mTouchSlop * 3)) && (xDiff > yDiff)) {

                        isDrag = true;
                        event.setAction(MotionEvent.ACTION_CANCEL);
                    }

                    break;
                }
                case MotionEvent.ACTION_UP: {
                    if (isDrag) {

                        final VelocityTracker velocityTracker = mVelocityTracker;
                        velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                        final float xVelocity = (int) velocityTracker.getXVelocity();

                        isDrag = false;

                        if (mVelocityTracker != null) {
                            mVelocityTracker.recycle();
                            mVelocityTracker = null;
                        }

                        if (xVelocity > FLING_MIN_VELOCITY) {
                            onGestureBack();
                            event.setAction(MotionEvent.ACTION_CANCEL);
                        }
                    }
                    break;
                }

                case MotionEvent.ACTION_CANCEL: {
                    mVelocityTracker.recycle();
                    mVelocityTracker = null;
                    isDrag = false;
                    break;
                }
            }
        }

        return super.dispatchTouchEvent(event);
    }

    /* 子类是否响应手势返回
    * @return 默认返回true，支持手势返回。
    */
    protected boolean isOnGestureBack(MotionEvent event) {
        return false;
    }

    /**
     * 子类可以重写此方法来处理手势返回时需要进行的操作；
     * 默认与返回键一致
     */
    protected void onGestureBack() {
        this.finish();
    }

    @Override
    public void alert(String title, String msg, String positive,
                      DialogInterface.OnClickListener positiveListener, String negative,
                      DialogInterface.OnClickListener negativeListener) {
        mActivityHelper.alert(title, msg, positive, positiveListener, negative, negativeListener);
    }

    @Override
    public void alert(String title, String msg, String positive,
                      DialogInterface.OnClickListener positiveListener, String negative,
                      DialogInterface.OnClickListener negativeListener,
                      Boolean isCanceledOnTouchOutside) {
        mActivityHelper.alert(title, msg, positive, positiveListener, negative, negativeListener,
                isCanceledOnTouchOutside);
    }

    @Override
    public void toast(String msg, int period) {
        mActivityHelper.toast(msg, period);
    }

    @Override
    public void showProgressDialog(String msg) {
        mActivityHelper.showProgressDialog(msg);
    }

    @Override
    public void showProgressDialog() {
        mActivityHelper.showProgressDialog(null);
    }

    public void showProgressDialog(final String msg, final boolean cancelable,
                                   final DialogInterface.OnCancelListener cancelListener) {
        mActivityHelper.showProgressDialog(msg, cancelable, cancelListener);
    }

    @Override
    public void dismissProgressDialog() {
        mActivityHelper.dismissProgressDialog();
    }

}
